package com.yanwq.sayhi.common.client;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.sayhi.common.constant.HttpConstant;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 作者：yanweiqiang。
 * 日期：2016/6/20 0020。
 */
public class OkRestClient {

    private OkHttpClient mClient;
    private Handler mHandler;
    private static OkRestClient instance;

    public OkRestClient() {
        super();
        mClient = new OkHttpClient();
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static OkRestClient getInstance() {
        syncInit();
        return instance;
    }

    private static synchronized void syncInit() {
        instance = new OkRestClient();
    }

    public Call get(final Context context, String url, OkRequestParams params, final OkResponseCallback callback) {
        return getDirect(context, getAbsoluteUrl(url), params, callback);
    }

    public Call getDirect(final Context context, String url, OkRequestParams params, final OkResponseCallback callback) {
        if (params != null) {
            url = url.concat(params.get());
        }

        callback.onStart();

        Request request = new Request.Builder().url(url).get().build();
        Call call = mClient.newCall(request);
        callback.call = call;

        try {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFail(0, null, e);
                            callback.onStop();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    handleResult(context, response, callback);
                }
            });

        } catch (final Exception e) {
            e.printStackTrace();
            ((Activity) context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onFail(0, null, e);
                    callback.onStop();
                }
            });
        }

        return call;
    }

    public Call post(final Context context, String url, OkRequestParams params, final OkResponseCallback callback) {
        callback.onStart();

        Request request = new Request.Builder().url(getAbsoluteUrl(url)).post(params.getRequestBody()).build();
        Call call = mClient.newCall(request);
        callback.call = call;

        try {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFail(0, null, e);
                            callback.onStop();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    handleResult(context, response, callback);
                }
            });
        } catch (final Exception e) {
            e.printStackTrace();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onFail(0, null, e);
                    callback.onStop();
                }
            });
        }
        return call;
    }

    public JSONObject post(String url, OkRequestParams params) {

        Request request = new Request.Builder().url(getAbsoluteUrl(url)).post(params.getRequestBody()).build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response.code() == 200) {
                return JSON.parseObject(String.valueOf(response.body()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public Call post(final Context context, String url, Object object, final OkResponseCallback callback) {
        callback.onStart();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(object));
        Request request = new Request.Builder().url(getAbsoluteUrl(url)).post(requestBody).build();
        Call call = mClient.newCall(request);
        callback.call = call;

        try {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFail(0, null, e);
                            callback.onStop();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    handleResult(context, response, callback);
                }
            });
        } catch (final Exception e) {
            e.printStackTrace();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onFail(0, null, e);
                    callback.onStop();
                }
            });
        }

        return call;
    }

    public JSONObject post(String url, Object object) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(object));
        Request request = new Request.Builder().url(getAbsoluteUrl(url)).post(requestBody).build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response.code() == 200) {
                return JSON.parseObject(response.body().string());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private void handleResult(Context context, final Response response, final OkResponseCallback callback) {

        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onStop();
                    }
                });
                return;
            }
        }

        if (!(context instanceof Activity)) {
            return;
        }

        final int code = response.code();

        if (code == 200) {
            final Object obj = callback.parse(response);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (obj == null) {
                        callback.onFail(code, "socket timeout.", new Throwable("socket timeout."));
                        callback.onStop();
                    } else {
                        callback.onSuccess(obj);
                    }
                    callback.onStop();
                }
            });
        }

        if (code > 200) {
            try {
                final String body = response.body().string();

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(code, body, new Throwable(body));
                        callback.onStop();
                    }
                });
            } catch (final IOException e) {
                e.printStackTrace();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(code, e.getMessage(), e);
                        callback.onStop();
                    }
                });
            }
        }
    }

    protected String getAbsoluteUrl(String url) {
        return HttpConstant.server.concat(url);
    }
}
